<script setup>
import { computed } from "vue";

const emit = defineEmits(["update:modelValue", "clear", "change"]);
const props = defineProps({
  modelValue: {
    type: String || Number,
    default: "",
  },
  option: {
    type: Array,
    default: [],
  },
  disabled: {
    type: Boolean,
    default: false,
  },
  placeholder: {
    type: String,
    default: "请选择",
  },
  isValue: {
    type: Boolean,
    default: false,
  },
  clearable: {
    type: Boolean,
    default: true,
  },
  multiple: {
    type: Boolean,
    default: false,
  },
});

const data = ref("");

watch(
  () => props.modelValue,
  (val) => {
    data.value = val;
  },
  { deep: true, immediate: true }
);

const arr = computed(() => {
  if (!Array.isArray(props.option)) {
    console.error(new Error("p-select组件:option数据类型错误,需要数组类型"));
    return [];
  } else {
    return props.option.map((t) => ({
      label: t.label || "label错误",
      value: t.value || "value错误",
    }));
  }
});

const change = () => {
  emit("update:modelValue", data.value);
  emit("change", data.value);
};
</script>

<template>
  <el-select
    :multiple="props.multiple"
    filterable
    :disabled="props.disabled"
    :clearable="props.clearable"
    v-model="data"
    :placeholder="placeholder"
    @clear="emit('clear')"
    @change="change"
  >
    <el-option
      :label="item.label"
      :value="item.value"
      v-for="item in arr"
      :key="item.value"
    >
      <span style="float: left">{{ item.label }}</span>
      <span
        v-if="isValue"
        style="
          float: right;
          color: var(--el-text-color-secondary);
          font-size: 13px;
          margin-left: 15px;
        "
        >{{ item.value }}</span
      >
    </el-option>
  </el-select>
</template>
<style scoped lang="scss"></style>
